import React, {useEffect, useState, useRef} from 'react'
import {
	Button,
	Space,
	Row,
	Col,
	message,
	Popconfirm,
	Tag,
	Modal,
	Form,
	Select,
} from 'antd'
import type {ColumnsType} from 'antd/es/table'
import {history, connect} from 'umi'
import Permissions from '@/components/Permissions'
import styles from './index.less'
import SearchForm from '@/components/SearchForm'
import CustomTable from '@/components/Table'
import {downloadByUrl} from '@/service/common/download'
import {
	getTableList,
	deleteModel,
	editConfigure,
} from '@/service/workflow/model'
// import {formatDate} from '@/utils/common/dateFilter'

import {getDict} from '@/service/common/dict'

const formItemLayout = {
	labelCol: {flex: '80px'},
	wrapperCol: {flex: '1'},
}
const model = (props: {dispatch: any; user: any}) => {
	const orgId = props?.user?.orgId
	const [params, setParams] = useState({
		current: 1,
		size: 10,
	})

	const [total, setTotal] = useState(0)
	const [loading, setLoading] = useState(false)
	const [modelId, setModelId] = useState<string>('')
	const [tableList, setTableList] = useState<any[]>([])
	const [searchData, setSearchData] = useState({})
	const [formData, setFormData] = useState<any[]>([])
	const [isModalOpen, setIsModalOpen] = useState(false)
	const [form] = Form.useForm()
	const [selectId, setSelectId] = useState('')
	const [dict, setDict] = useState({
		Process_Type: [],
	})
	// 获取表格数据
	const onListFun = () => {
		setLoading(true)
		getTableList({...params, ...searchData})
			.then((res: any) => {
				if (res?.data?.records) {
					setTableList(() => res?.data?.records)
					setTotal(() => res?.data?.total)
					setLoading(false)
				}
			})
			.catch(() => {
				setLoading(false)
			})
	}

	// 删除事件
	const onDeleteFun = (ids?: any) => {
		const id = ids || selectId
		deleteModel({id})
			.then((res: any) => {
				if (res.success) {
					message.success(res.msg)
					onListFun()
				}
			})
			.catch((err) => {
				message.error(err)
			})
	}

	// 列表
	const columns: ColumnsType<contractAPI.ContractColumns> = [
		{
			title: '序号',
			dataIndex: 'order',
			align: 'center',
			width: 70,
			render(text, record, index) {
				return <span>{(params.current - 1) * 10 + index + 1}</span>
			},
		},
		{
			title: '模型主键',
			dataIndex: 'id',
			align: 'center',
			width: 300,
		},
		{
			title: '模型标识',
			dataIndex: 'key',
			align: 'center',
			width: 150,
		},
		{
			title: '模型名称',
			dataIndex: 'name',
			align: 'center',
			width: 150,
		},
		{
			title: '流程版本',
			dataIndex: 'version',
			align: 'center',
			width: 150,
			render: (text) => <Tag color="red">v{text}</Tag>,
		},
		// {
		// 	title: '创建时间',
		// 	dataIndex: 'createTime',
		// 	align: 'center',
		// 	width: 150,
		// 	render(text: any) {
		// 		return (
		// 			<span>
		// 				{text ? formatDate(text, 'YYYY-MM-DD HH:mm:ss') : '--'}
		// 			</span>
		// 		)
		// 	},
		// },
		// {
		// 	title: '更新时间',
		// 	dataIndex: 'lastUpdeTime',
		// 	align: 'center',
		// 	width: 150,
		// 	render(text: any) {
		// 		return (
		// 			<span>
		// 				{text ? formatDate(text, 'YYYY-MM-DD HH:mm:ss') : '--'}
		// 			</span>
		// 		)
		// 	},
		// },
		{
			title: '操作',
			key: 'action',
			align: 'center',
			fixed: 'right',
			width: 250,
			render: (text, record: any) => (
				<div>
					<Permissions permissionID="amc_system_workflow_model_set">
						<Button
							type="link"
							size="small"
							onClick={() => {
								history.push({
									pathname: '/workflow/model/configure',
									query: {
										id: record.id,
									},
								})
							}}>
							配置
						</Button>
					</Permissions>
					<Permissions permissionID="amc_system_workflow_model_deploy">
						<Button
							type="link"
							size="small"
							onClick={() => {
								setModelId(() => record.id)
								setIsModalOpen(true)
								form.resetFields()
							}}>
							部署
						</Button>
					</Permissions>
					<Permissions permissionID="amc_system_workflow_model_delete">
						<Popconfirm
							placement="topLeft"
							title="你确定要删除这条模型吗？"
							onConfirm={() => onDeleteFun(record.id)}
							okText="确定"
							cancelText="取消">
							<Button type="link" size="small">
								删除
							</Button>
						</Popconfirm>
					</Permissions>
					<Permissions permissionID="amc_system_workflow_model_downLoad">
						<Button
							type="link"
							size="small"
							className="downOrupload"
							onClick={() => {
								downloadByUrl(
									`${
										window.apiPrefixUri || ''
									}/workflow/api/promise/app/rest/models/${
										record.id
									}/bpmn20`,
									`${record.name}.xml`,
								)
							}}>
							下载
						</Button>
						{/* <a
							href={`/workflow/api/promise/app/rest/models/${record.id}/bpmn20`}
							download={`${record.name}.xml`}
							title="导出到BPMN2">
							下载
						</a> */}
					</Permissions>
				</div>
			),
		},
	]

	const onFinish = (values: any) => {
		setSearchData(values)
	}

	// 搜索重置
	const onReset = () => {
		setSearchData({})
	}

	// 初始化分页
	useEffect(() => {
		const param = {
			current: 1,
			size: 10,
		}
		setParams(() => param)
	}, [searchData])
	// 获取表格数据
	// 自定义一个初始不更新的hook
	const useUpdateEffect = (fn: Function, inputs: any[]) => {
		const didMountRef = useRef(false)
		useEffect(() => {
			if (didMountRef.current) fn()
			else didMountRef.current = true
		}, inputs)
	}

	// 使用自定义hook
	useUpdateEffect(onListFun, [params])

	useEffect(() => {
		getDict(
			{
				dictKeys: ['Process_Type'],
			},
			(res: any) => {
				setDict(res)
			},
		)
		const formItems: any[] = [
			{
				type: 'group',
				key: 'group1',
				groupItems: [
					{
						type: 'input',
						label: '模型标识',
						name: 'identification',
						key: 'identification',
					},
					{
						type: 'input',
						label: '模型名称',
						name: 'processName',
						key: 'processName',
					},
					{},
				],
			},
		]
		setFormData(formItems)
	}, [])

	const submit = async () => {
		const submitData = await form.validateFields()
		const formD = new FormData()
		formD.append('modelId', modelId)
		formD.append('tenantId', orgId)
		formD.append('categoryp', submitData.categoryp)
		editConfigure(formD)
			.then((res) => {
				if (res.success) {
					setIsModalOpen(false)
					message.success(res.msg)
					onListFun()
				}
			})
			.catch((err) => {
				message.error(err)
			})
	}
	const onCancel = () => {
		form.resetFields()
		setIsModalOpen(false)
	}

	return (
		<div className={styles.page}>
			<div className="search">
				{formData && (
					<SearchForm
						onFinish={onFinish}
						onReset={onReset}
						formItems={formData}
						formLayout={formItemLayout}
					/>
				)}
			</div>
			<div className="btnlist">
				<Space size={12}>
					<Permissions permissionID="amc_system_workflow_model_create">
						<Button
							type="primary"
							ghost
							size="small"
							onClick={() => {
								history.push('/workflow/model/add')
							}}>
							创建
						</Button>
					</Permissions>
					<Permissions permissionID="amc_system_workflow_model_delete">
						<Button
							type="primary"
							ghost
							danger
							size="small"
							onClick={() => onDeleteFun()}>
							删除
						</Button>
					</Permissions>
				</Space>
			</div>
			<div className="table">
				<CustomTable
					params={params}
					columns={columns}
					kid="id"
					callback={(pagination: any) => {
						setParams(pagination)
					}}
					pagination
					loading={loading}
					dataSource={tableList}
					total={total}
					showRowSelection
					selectCallback={(keys: any) => {
						setSelectId(() => keys?.join(','))
					}}
				/>
			</div>
			<Modal
				title="流程部署配置"
				open={isModalOpen}
				onOk={submit}
				onCancel={onCancel}
				width={500}
				destroyOnClose
				footer={
					<>
						<Button size="small" onClick={onCancel}>
							取消
						</Button>
						<Button type="primary" size="small" onClick={submit}>
							确定
						</Button>
					</>
				}>
				<Form
					form={form}
					name="basic"
					layout="horizontal"
					labelCol={{flex: '90px'}}
					labelAlign="right"
					labelWrap
					initialValues={{remember: true}}
					autoComplete="off">
					<Row gutter={12}>
						<Col span={24}>
							<Form.Item
								label="流程类型"
								name="categoryp"
								rules={[
									{
										required: true,
									},
								]}>
								<Select
									placeholder="请选择"
									allowClear
									fieldNames={{
										value: 'dictKey',
										label: 'dictValue',
									}}
									options={[...dict.Process_Type]}
								/>
							</Form.Item>
						</Col>
					</Row>
				</Form>
			</Modal>
		</div>
	)
}
export default connect(({user}: any) => ({
	user,
}))(model)
